﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Codecs.Http;
using DotNetty.Transport.Channels;

namespace ME860.DotNetty.Server.CoreImpl
{
    class ChannelHandler : SimpleChannelInboundHandler<object>
    {
        protected override void ChannelRead0(IChannelHandlerContext ctx, object msg)
        {
            if (msg is IFullHttpRequest request)
            {
                if (!request.Result.IsSuccess)
                {
                    SendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.BadRequest));
                    return;
                }
                SendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK));
            }
        }

        private void SendHttpResponse(IChannelHandlerContext ctx, IFullHttpResponse response)
        {
            Task task = ctx.Channel.WriteAndFlushAsync(response);
            task.ContinueWith(async (t, obj) =>
            {
                if (obj is IChannelHandlerContext channelHandler)
                {
                    await channelHandler.CloseAsync();
                }
            }, ctx, TaskContinuationOptions.ExecuteSynchronously);
        }
    }
}
